// pages/car/car.js
import { getstorage } from '@/miniprogram/utils/storage'
import { userStore } from '@/stores/userStore'
const computedBehavior = require("miniprogram-computed").behavior;
import { getCartList, changeCount, deleteCartCount, changeStatus, changeCheckAll, submitCar } from '@/miniprogram/utils/API/car'
Component({
    behaviors: [computedBehavior],
    /**
     * 页面的初始数据
     */
    data: {
        fromCar: false,
        token: '',
        checkedAll: 0,
        cartList: { items: null },
        height: 0,
        width: 0,
        sendData: {
            skuId: '',
            count: '',
            selectStatusL: ''
        }
    },
    computed: {
        selectAllStatus(data) {
            return data.cartList.items != null && data.cartList.items.every(item => item.selectStatus === 1)
        }
    },

    methods: {
        /**
         * 生命周期函数--监听页面初次渲染完成
         */
        onReady() {
            let height = wx.getWindowInfo().windowHeight
            let width = wx.getWindowInfo().windowWidth
            height = height - 70 + 'px'
            this.setData({
                height,
                width,
            })
        },

        bindcheckChange(e) {
            let isChecked = e.detail
            let { skuid } = e.target.dataset
            let { cartList, sendData, checkedAll } = this.data
            sendData.skuId = parseInt(skuid)
            sendData.selectStatus = isChecked == true ? 1 : 0
            //设置改变属性
            cartList.items.forEach(i => {
                if (i.skuId == skuid) {
                    sendData.count = i.count
                    this.changeStatusFun(sendData)
                }
            })
            this.setData({
                checkedAll,
                cartList
            })
        },
        checkAllbtn(e) {
            let { detail } = e
            console.log(e);
            let { cartList, checkedAll } = this.data
            checkedAll = detail == false ? 0 : 1
            let data = {}
            data.checkAll = checkedAll
            this.setData({
                checkedAll
            })
            this.changeCheckAllFun(data)
        },
        submit(e) {
            let { cartList, fromCar } = this.data
            fromCar = true
            let skuId = cartList.items[0].skuId
            if (cartList.totalAmount <= 0) {
                wx.showToast({
                    title: '请选择商品！',
                    icon: 'error'
                })
                return
            }
            wx.redirectTo({
                url: `/miniprogram/pre_loadModules/orderModule/pages/orderCheck/orderCheck?fromCar=${fromCar}&skuId=${skuId}`,
            })
        },

        async changeStatusFun(data) {
            let res = await changeStatus(data)
            if (res.data.code == 200) {
                this.getCartListFromService()
            }
        },

        async changeCheckAllFun(data) {
            let res = await changeCheckAll(data)
            if (res.data.code == 200) {
                this.getCartListFromService()
            }
        },

        async submitCarFun() {
            let res = await submitCar()
        },

        async getCartListFromService() {
            let { cartList } = this.data
            let res = await getCartList()
            cartList = res.data.data
            let result = []
            if (cartList.items != null) {
                cartList.items.forEach(item => {
                    let r = []
                    item.skuAttrs.forEach(i => {
                        r.push(i.split('：')[1])
                    })
                    item.price = item.price.toFixed(2)
                    item.totalPrice = item.totalPrice.toFixed(2)
                    item.skuAttrs = r
                })
                cartList.totalAmount = cartList.totalAmount.toFixed(2)
            }

            this.setData({
                cartList
            })
        },
        //删除购物车
        deleteCartItem(e) {
            let { skuid, selected } = e.currentTarget.dataset
            let data = {}
            data.skuId = skuid
            wx.showModal({
                title: "确定要删除吗"
            }).then(() => {
                this.delectCar(data)
            }).catch(e => {
                wx.showToast({
                    title: e.message,
                    icon: 'error'
                })
            })

        },
        bindinputblur(e) {
            let { skuid, selected } = e.currentTarget.dataset
            let { cartList, sendData } = this.data
            sendData.skuId = skuid
            sendData.selectStatusL = selected
            sendData.count = e.detail.value
            cartList.items.forEach(i => {
                if (i.skuId == skuid) {
                    i.count = e.detail.value
                    this.changeCountfunction(sendData)
                }
            })
        },
        bindplus(e) {
            let { skuid, selected } = e.currentTarget.dataset
            let { cartList, sendData } = this.data
            sendData.skuId = skuid
            sendData.selectStatusL = selected
            cartList.items.forEach(i => {
                if (i.skuId == skuid) {
                    i.count += 1
                    sendData.count = i.count
                    this.changeCountfunction(sendData)
                }
            })
        },
        bindminus(e) {
            let { skuid, selected } = e.currentTarget.dataset
            let { cartList, sendData } = this.data
            sendData.skuId = skuid
            sendData.selectStatusL = selected
            cartList.items.forEach(i => {
                if (i.skuId == skuid) {
                    if (i.count > 1) {
                        i.count -= 1
                        sendData.count = i.count
                    } else if (i.count <= 1) {
                        i.count = 1
                        sendData.count = i.count
                    }
                    this.changeCountfunction(sendData)
                }
            })
        },
        /**
         * 生命周期函数--监听页面显示
         */
        onShow() {
            let { token } = this.data
            token = getstorage('token')[0];
            if (token) {
                this.getCartListFromService()
            }
            this.setData({
                token
            })
        },

        async delectCar(data) {
            let res = await deleteCartCount(data)
            if (res.data.code == 200) {
                wx.showToast({
                    title: '删除成功',
                })
                this.getCartListFromService()
            }
        },

        async changeCountfunction(data) {
            let res = await changeCount(data)
            if (res.data.code == 200) {
                this.getCartListFromService()
            }
        },
        immediatelyLogin() {
            wx.navigateTo({
                url: '/pages/login/login',
            })
        },
        immediatelyAddCar() {
            wx.switchTab({
                url: '/pages/index/index',
            })
        },

    }
})